package com.lantosec.hmrp.core.util.sms;

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;

import java.util.Map;

public class SmsUtils {
    private static SubmitResult send(NameValuePair[] data) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(Config.URL);
        client.getParams().setContentCharset("utf-8");
        method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=utf-8");
        method.setRequestBody(data);
        try {
            client.executeMethod(method);
            String res = method.getResponseBodyAsString();
            return JSON.parseObject(res, SubmitResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 发关短信
     *
     * @param mobile  手机号
     * @param content 短信内容
     * @return
     */
    public static SubmitResult send(String mobile, String content) {
        if (StringUtils.isNotEmpty(mobile) && StringUtils.isNotEmpty(content)) {
            NameValuePair[] data = {
                    new NameValuePair("account", Config.ACCOUNT),
                    new NameValuePair("password", Config.APIKEY),
                    new NameValuePair("mobile", mobile),
                    new NameValuePair("content", content),
                    new NameValuePair("format", "json")
            };
            return send(data);
        }
        return null;
    }

    /**
     * 使用模板字符串发送短信
     *
     * @param mobile         手机号
     * @param templateString 短信内容模板
     * @param variable       模板变量集合
     * @return
     */
    public static SubmitResult send(String mobile, String templateString, Map<String, String> variable) {
        StringSubstitutor sub = new StringSubstitutor(variable);
        String content = sub.replace(templateString);
        return send(mobile, content);
    }

    /**
     * 使用系统提供模板ID发送短信
     *
     * @param mobile     手机号
     * @param templateId 模板ID
     * @param content    模板中变量值集合
     * @return
     */
    public static SubmitResult send(String mobile, String templateId, String[] content) {
        String _content = "";
        if (content != null && content.length > 0) {
            _content = StringUtils.join(content, "|");
        }
        NameValuePair[] data = {
                new NameValuePair("account", Config.ACCOUNT),
                new NameValuePair("password", Config.APIKEY),
                new NameValuePair("mobile", mobile),
                new NameValuePair("templateid", templateId),
                new NameValuePair("content", _content),
                new NameValuePair("format", "json")
        };
        return send(data);
    }
}
